package com.coolweather.app.textcool.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.coolweather.app.textcool.R;
import com.coolweather.app.textcool.service.AutoUpdateService;
import com.coolweather.app.textcool.util.HttpCallbackListener;
import com.coolweather.app.textcool.util.HttpUtil;
import com.coolweather.app.textcool.util.Utility;

public class WeatherActivity extends AppCompatActivity implements View.OnClickListener {
    private LinearLayout weatherInfoLayout;
    private TextView cityNameText;//城市名
    private TextView publishText;//发布时间
    private TextView weatherDespText;//天气描述
    private TextView temp1Text;//温度1
    private TextView temp2Text;//温度2
    private TextView currentDateText;//当前时间
    private Button   switchCity;//切换城市
    private Button   refreshWeather;//刷新天气

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.weather_layout);
        //初始化各个控件
        weatherInfoLayout=(LinearLayout)findViewById(R.id.weather_info_layout);
        cityNameText=(TextView)findViewById(R.id.city_name);
        publishText=(TextView)findViewById(R.id.publish_text);
        weatherDespText=(TextView)findViewById(R.id.weather_desp);
        temp1Text=(TextView)findViewById(R.id.temp1);
        temp2Text=(TextView)findViewById(R.id.temp2);
        currentDateText=(TextView)findViewById(R.id.current_date);
        switchCity=(Button) findViewById(R.id.switch_city);
        refreshWeather=(Button)findViewById(R.id.refresh_weather);
        //获取传来的countyCode
        String countyCode=getIntent().getStringExtra("county_code");
        if(!TextUtils.isEmpty(countyCode)){
            publishText.setText("加载中...");
            weatherInfoLayout.setVisibility(View.INVISIBLE);
            cityNameText.setVisibility(View.INVISIBLE);
            queryWeatherCode(countyCode);
        }else{
            showWeather();
        }
        switchCity.setOnClickListener(this);
        refreshWeather.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.switch_city:
                Intent intent=new Intent(this,ChooseAreaActivity.class);
                intent.putExtra("from_weather_activity", true);
                startActivity(intent);
                finish();
                break;

            case R.id.refresh_weather:
                publishText.setText("同步中...");
                SharedPreferences pref= PreferenceManager.getDefaultSharedPreferences(this);
                String weatherCode=pref.getString("weather_code","");
                if(!TextUtils.isEmpty(weatherCode)){
                    queryWeatherInfo(weatherCode);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 查询县级代号对应的天气状况
     * @param countyCode
     */
        private void queryWeatherCode(String countyCode){
            String address="http://www.weather.com.cn/data/list3/city"+countyCode+".xml";
            queryFromServer(address,"countyCode");
        }

    /**
     * 查询天气代号对应的天气状况
     * @param weatherCode
     */
    private void queryWeatherInfo(String weatherCode){
        String address="http://www.weather.com.cn/data/cityinfo/"+weatherCode+".html";
        queryFromServer(address,"weatherCode");
    }

    /**
     * 根据传入的地址和类型去向服务器查询天气代号或者天气信息
     * @param address 服务器查询地址
     * @param type 查询类型，countyCode县级代号/weatherCode天气代号
     */
    private void queryFromServer(final String address,final String type){
        //调用sendHttpRequest工具方法，查询服务器，在onFinish()中做json解析
        HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {
            @Override
            public void onFinish(final String response) {
                //countyCode解析xml获取天气代码
                if("countyCode".equals(type)){
                    if(!TextUtils.isEmpty(response)){
                        String[] array=response.split("\\|");
                        if(array!=null&&array.length==2){
                            String weatherCode=array[1];
                            queryWeatherInfo(weatherCode);
                        }
                    }
                    //weatherCode解析json获取、存储并显示天气信息
                }else if("weatherCode".equals(type)){
                    Utility.handleWeatherResponse(WeatherActivity.this,
                            response);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showWeather();
                        }
                    });
                }
            }

            @Override
            public void onError(Exception e) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    publishText.setText("同步失败...");
                }
            });
            }
        });

    }
    /**
     *从SharedPrefences文件中读取存储的天气信息，并显示在界面上
     */
    private void showWeather(){
        SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(this);
        cityNameText.setText(pref.getString("city_name",""));
        temp1Text.setText(pref.getString("temp1",""));
        temp2Text.setText(pref.getString("temp2",""));
        weatherDespText.setText(pref.getString("weather_desp",""));
        publishText.setText("今天"+pref.getString("publish_time","")+"发布");
        currentDateText.setText(pref.getString("current_date", ""));
        weatherInfoLayout.setVisibility(View.VISIBLE);
        cityNameText.setVisibility(View.VISIBLE);
        Intent intent=new Intent(this, AutoUpdateService.class);
        startService(intent);

    }

}
